//
//  LtqCycleImages.m
//  UI16_UICollectionViewCycleImage
//
//  Created by Hanlingyu on 16/8/4.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "LtqCycleImages.h"
#define kCollectionViewReuse @"reuse"
@interface LtqCycleImages ()
<
    UICollectionViewDelegate,
    UICollectionViewDataSource
>

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *titleLabel;


@end

@implementation LtqCycleImages

// 用代码创建就走初始化方法
- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
//        self.backgroundColor = [UIColor redColor];
        [self setUp];
        
    }
    return self;
}

// 用SB或xib创建走此方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
//        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}

- (void)setUp {
    
    [self createCollectionView];
    [self createPageControl];
    [self addTimer];
    [self createTitleLabel];

}

- (void)createCollectionView {
    
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _cycleCollectionView.pagingEnabled = YES;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.delegate = self;
    [self addSubview:_cycleCollectionView];
    
    
    
    [_cycleCollectionView registerClass: [LtqCycleImagesCell class] forCellWithReuseIdentifier:kCollectionViewReuse];
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _array.count;
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LtqCycleImagesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewReuse forIndexPath:indexPath];
    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    
#warning 可以在此用代理方法改变cell中的内容

    if (self.dataSource && [self.dataSource respondsToSelector:@selector(handleDataWithObject:cell:)]) {
        [self.dataSource handleDataWithObject:_array[indexPath.row] cell:cell];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.delegate cellClicked:indexPath];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    _pageControl.currentPage = scrollView.contentOffset.x / self.bounds.size.width - 1;
    // 直接判断与0相等有何问题
    if (scrollView.contentOffset.x == 0) {
    [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        [_pageControl setCurrentPage:_array.count - 2];
    } else if (scrollView.contentOffset.x == _cycleCollectionView.bounds.size.width * (_array.count - 1)) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        _pageControl.currentPage = 0;
    }
    _titleLabel.text = [NSString stringWithFormat:@"第%ld页", _pageControl.currentPage + 1];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
//    [_timer invalidate];
    [self removeTimer];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    [self addTimer];
    
    
}


- (void)createPageControl {
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    [self addSubview:_pageControl];
    
    
}

- (void)createTimer {
    // 仅仅是创建, 并没有加在loop中
    // 下面方法必须加在runLoop中, 才能开始计时
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(imageChange) userInfo:nil repeats:YES];
    
    // 创建一个timer并添加到loop中
    // 下面方法已经被加在runLoop中, 所以开始就能计时
//    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(imageChange) userInfo:nil repeats:YES];
    // NSRunLoopCommonModes 和 NSDefaultRunLoopMode
    // 后者代表默认状态, scheduledTimeWithTimeInterVal添加为默认状态
    // 前者为多种状态, 包含 默认 及 滚动
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

    // 取消timer, 调用invalidate
    [_timer invalidate];
    // _timer制空
    _timer = nil;
}

- (void)addTimer {
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(imageChange) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

    
}

- (void)removeTimer {
    // 取消timer, 调用invalidate
    [_timer invalidate];
    // _timer制空
    _timer = nil;
    
}

- (void)createTitleLabel {
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleLabel.backgroundColor = [UIColor blackColor];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.textAlignment = 1;
    _titleLabel.text = @"第一页";
    [self addSubview:_titleLabel];
}



- (void)imageChange {
    CGFloat i = _cycleCollectionView.contentOffset.x + self.bounds.size.width;
//    NSLog(@"%lf", i);
    [_cycleCollectionView setContentOffset:CGPointMake(i, 0) animated:YES];
    if (i == (_array.count - 1) * self.bounds.size.width) {
        _cycleCollectionView.contentOffset = CGPointMake(0, 0);
    }
    _pageControl.currentPage = (_cycleCollectionView.contentOffset.x + self.bounds.size.width) / self.bounds.size.width - 1;
    _titleLabel.text = [NSString stringWithFormat:@"第%ld页", _pageControl.currentPage + 1];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _cycleCollectionView.frame = self.bounds;
    _flowLayout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _pageControl.frame = CGRectMake(0, 0, self.bounds.size.width, 20);
    _pageControl.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - 10);
    _titleLabel.frame = CGRectMake(self.bounds.size.width - 70, self.bounds.size.height - 30, 70, 30);

}


- (void)setArray:(NSArray *)array {
    _array = array;
    [_cycleCollectionView reloadData];
    _pageControl.numberOfPages = array.count - 2;
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end



// .m
@implementation LtqCycleImagesCell

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
    }
    return self;
}


@end



